package com.jeeplus.modules.api.utils.Esaipay.Http;

import java.security.MessageDigest;
import java.math.BigInteger;
//import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.HashMap;

public class ParameterBuilder {
	//private String charsetName = "utf-8";
	// private String signKey = "";

	// public void setSignKey(String signKey) {
	// this.signKey = signKey;
	// }

//	public void setCharsetName(String charsetName) {
//		this.charsetName = charsetName;
//	}

	
	HashMap<String, String> map = new HashMap<String, String>();
	HashMap<String, String> encodeMap = new HashMap<String, String>();

	public ParameterBuilder() {
		// TODO Auto-generated constructor stub

	}

//	public ParameterBuilder(String charsetName) {
//		// TODO Auto-generated constructor stub
//		this.charsetName = charsetName;
//	}

	public void put(String key, String value) {
		map.put(key, value);
	}

	public void put(String key, String value, String charsetName) {
		try {
			map.put(key, value);
			if (charsetName == null || "".equals(charsetName.trim())) {
				charsetName = "utf-8";
			}
			encodeMap.put(key, URLEncoder.encode(value, charsetName));
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}

	@Override
	public String toString() {
		return this.toString(true);
	}
	
	private String toString(boolean encode){
		StringBuilder sb = new StringBuilder();
		try {		
			String[] keyArr = map.keySet().toArray(new String[0]);   
			Arrays.sort(keyArr);
			
			for (String key : keyArr) {
				String value = map.get(key);
				if (encode && encodeMap.containsKey(key)) {				
					value = encodeMap.get(key);
				}
				sb.append(key.toLowerCase()).append("=").append(value).append("&");
			}
			sb.deleteCharAt(sb.lastIndexOf("&"));
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
//		System.out.println(sb.toString());
		return sb.toString();
	}

	/**
	 * MD5签名
	 * @param signKey
	 * @return
	 */
	public String sign(String signKey) {
		String result = "";
		String data = this.toString(false);
		if (signKey != null) {
			data = data + signKey.trim();
		}
//		System.out.println("用来签名的参数：");
//		System.out.println(data);
		try {
			// 生成一个MD5加密计算摘要
			MessageDigest md = MessageDigest.getInstance("MD5");
			// 计算md5函数
			md.update(data.getBytes());
			// digest()最后确定返回md5 hash值，返回值为8为字符串。因为md5 hash值是16位的hex值，实际上就是8位的字符
			// BigInteger函数则将8位的字符串转换成16位hex值，用字符串来表示；得到字符串形式的hash值
			BigInteger bi = new BigInteger(1, md.digest());
			// data = bi.toString(16);
			// BigInteger会把0省略掉，需补全至32位
			result = String.format("%032x", bi); // 左侧用0补够32位长度 prints:
													// 00000000000000000093
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
//		System.out.println("签名结果");
//		System.out.println(result);
		return result;
	}

}
